package ${packagePath}.common.ext;

import ${packagePath}.common.constant.Constants;
import ${packagePath}.model.to.ResultTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.stream.Collectors;

/**
 * 全局异常处理类，根据异常类型，自动封装返回对象
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是ConstraintViolationException
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public ResultTo constraintViolationExceptionHandler(ConstraintViolationException e) {
        return ResultTo.fail(ResultTo.ResultCode.PARAME_ERR,
                e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(Constants.COMMA_CH)));
    }

    /**
     * 处理请求参数格式错误 @RequestBody上validate失败后抛出的异常是MethodArgumentNotValidException异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseBody
    public ResultTo methodArgumentNotValidHandler(MethodArgumentNotValidException e) {
        return ResultTo.fail(ResultTo.ResultCode.PARAME_ERR,
                e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage)
                        .collect(Collectors.joining(Constants.COMMA_CH)));
    }

    /**
     * 处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler({BindException.class})
    @ResponseBody
    public ResultTo bindExceptionHandler(BindException e) {
        return ResultTo.fail(ResultTo.ResultCode.PARAME_ERR,
                e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage)
                        .collect(Collectors.joining(Constants.COMMA_CH)));
    }

    /**
     * 参数异常类型异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler({IllegalArgumentException.class, IllegalStateException.class})
    @ResponseBody
    public ResultTo argumentExceptionHandler(RuntimeException e) {
        String code = e.getMessage();
        if (code.contains(Constants.HORIZONTAL_LINE)) {
            log.error("出现业务异常，{}", code);
            return ResultTo.fail(Integer.valueOf(code.substring(0, code.indexOf(Constants.HORIZONTAL_LINE))), code.substring(code.indexOf(Constants.HORIZONTAL_LINE) + 1));
        }
        ResultTo.ResultCode resultCode = ResultTo.ResultCode.PARAME_ERR;
        try {
            resultCode = ResultTo.ResultCode.valueOf(code);
        } catch (Exception e1) {
            log.error("异常枚举值找不到", e1);
        }

        return ResultTo.fail(resultCode, resultCode.getMsg());
    }

    /**
     * MethodArgumentNotValidException，采用javax.validation校验的异常
     *
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler({HttpMessageNotReadableException.class})
    @ResponseBody
    public ResultTo httpMessageNotReadableHandler(HttpServletRequest request, HttpMessageNotReadableException e) {
        return ResultTo.fail(ResultTo.ResultCode.PARAME_ERR, "JSON参数解析失败");
    }

    /**
     * 对于未给出的异常处理
     *
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler({NullPointerException.class, ClassCastException.class, ArrayIndexOutOfBoundsException.class,
            NumberFormatException.class, SQLException.class, IOException.class, NumberFormatException.class})
    @ResponseBody
    public ResultTo runtimeExceptionHandler(HttpServletRequest request, Exception e) {
        return commonExHandler(e);
    }

    /**
     * 通用异常实际处理类
     *
     * @param e
     * @return
     */
    private ResultTo commonExHandler(Exception e) {
        log.error("发生异常", e);
        return ResultTo.fail();
    }


}
